package com.flx.noodle.websocket.dao.impl;

import com.flx.noodle.websocket.dao.MessageDao;
import com.flx.noodle.websocket.dao.mapper.MessageRowMapper;
import com.flx.noodle.websocket.entity.ChatMessage;
import com.flx.noodle.websocket.searcher.MessageSearcher;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by fenglixiong on 2017/10/2.
 */
@Repository
public class MessageDaoImpl extends JdbcDaoSupport implements MessageDao {

    @Autowired
    MessageDaoImpl(@Qualifier("dataSource") DataSource dataSource){
        setDataSource(dataSource);
    }


    public ChatMessage getMessageById(int msgId) {
        JdbcTemplate _jdbc = this.getJdbcTemplate();
        String sql = "select * from ws_message where id = ?";
        List<ChatMessage> messageList = _jdbc.query(sql,new Object[]{msgId},new MessageRowMapper());
        return messageList.size()>0?messageList.get(0):null;
    }

    public int insertMessage(final ChatMessage chatMessage) {
        JdbcTemplate _jdbc = this.getJdbcTemplate();
        final String sql = "insert into ws_message (chat_id,user_id,user_name,content,content_type,content_size,create_time) values (?,?,?,?,?,?,now())";
        int ret = _jdbc.update(new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(sql);
                ps.setInt(1,chatMessage.getChatId());
                ps.setInt(2,chatMessage.getUserId());
                ps.setString(3,chatMessage.getUserName());
                ps.setString(4,chatMessage.getContent());
                ps.setString(5,chatMessage.getContentType());
                ps.setInt(6,chatMessage.getContentSize());
                return ps;
            }
        });
        return ret;
    }

    public int updateMessage(final ChatMessage chatMessage) {
        JdbcTemplate _jdbc = this.getJdbcTemplate();
        final String sql = "update ws_message set chat_id=?,user_id=?,user_name=?,content=?,content_type=?,content_size=? where id=?";
        int ret = _jdbc.update(new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(sql);
                ps.setInt(1,chatMessage.getChatId());
                ps.setInt(2,chatMessage.getUserId());
                ps.setString(3,chatMessage.getUserName());
                ps.setString(4,chatMessage.getContent());
                ps.setString(5,chatMessage.getContentType());
                ps.setInt(6,chatMessage.getContentSize());
                ps.setInt(7,chatMessage.getId());
                return ps;
            }
        });
        return ret;
    }

    public int deleteMessage(int msgId) {
        JdbcTemplate _jdbc = this.getJdbcTemplate();
        String sql = "delete from ws_message where id = ?";
        int ret = _jdbc.update(sql,new Object[]{msgId});
        return ret;
    }

    public List<ChatMessage> findMessageList(MessageSearcher searcher) {
        JdbcTemplate _jdbc = this.getJdbcTemplate();
        List<Object> params = new ArrayList<Object>();
        String sql = "select * from ws_message where 1 = 1 ";
        if(searcher.getChatId()!=null){
            sql += "and chat_id = ? ";
            params.add(searcher.getChatId());
        }
        if(searcher.getUserId()!=null){
            sql += "and user_id = ? ";
            params.add(searcher.getUserId());
        }
        if(searcher.getUserName()!=null){
            sql += "and user_name like ? ";
            params.add("%"+searcher.getUserName()+"%");
        }
        if(StringUtils.isNotBlank(searcher.getContent())){
            sql += "and content like ? ";
            params.add("%"+searcher.getContent()+"%");
        }
        if(StringUtils.isNotBlank(searcher.getContentType())){
            sql += "and content_type = ? ";
            params.add(searcher.getContentType());
        }
        String sql_count = "select count(*) from ("+sql+") s";
        int rowCount = _jdbc.queryForObject(sql_count,params.toArray(),Integer.class);
        searcher.setTotalResults(rowCount);
        sql += " order by id desc";
        //分页
        sql += " limit ? , ? ";
        params.add((searcher.getPage() - 1) * searcher.getPageSize());
        params.add(searcher.getPageSize());

        return _jdbc.query(sql,params.toArray(),new MessageRowMapper());
    }

    public ChatMessage getSystemMsg(int chatId, int userId) {
        JdbcTemplate _jdbc = this.getJdbcTemplate();
        String sql = "select * from ws_message where chat_id=? and user_id=? and create_time = (select max(create_time) maxTime from ws_message)";
        List<ChatMessage> chatMessages = _jdbc.query(sql,new Object[]{chatId,userId},new MessageRowMapper());
        return chatMessages.size()>0?chatMessages.get(0):null;
    }
}
